package com.acme.biz.web.mvc.exception;

import com.acme.biz.api.ApiResponse;
import com.acme.biz.api.enums.ResultEnum;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestControllerAdvice("com.acme.biz.web")
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse parameterExceptionHandler(MethodArgumentNotValidException e) {
       // log.error("参数校验不通过:{}", ExceptionUtils.getMessage(e));
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        List<String> errorList = new ArrayList<>();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if(!CollectionUtils.isEmpty(errors)){
                for(ObjectError error:errors){
                    FieldError fieldError = (FieldError)error;
                    errorList.add(fieldError.getDefaultMessage());
                }
            }
            if(!CollectionUtils.isEmpty(errorList))
                return ApiResponse.fail(ResultEnum.PARAM_ERROR.getCode(), String.join(",", errorList));
        }
        return ApiResponse.fail(ResultEnum.PARAM_ERROR);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public ApiResponse parameterExceptionHandler(ValidationException e) {
        return ApiResponse.fail(ResultEnum.PARAM_ERROR.getCode(),e.getMessage());
    }
}
